using Godot;

namespace BarbarianBlaster.Turret;

public partial class Turret : Node3D
{
    // 炮弹实体
    [Export] PackedScene _projectilePrefab;

    // 打击范围
    [Export] float _turretRange = 10.0f;
    private Node3D _cannon;
    private Node3D _turretBase;

    public Path3D EnemyPath;
    private PathFollow3D _enemyTarget;

    private AnimationPlayer _animationPlayer;
    
    public override void _Ready()
    {
        _animationPlayer=GetNode<AnimationPlayer>("AnimationPlayer");
        _cannon = GetNode<Node3D>("TurretBase/TurretTop/Cannon");
        _turretBase = GetNode<Node3D>("TurretBase");
    }

    public override void _PhysicsProcess(double delta)
    {
        // 炮塔总是对着最后一个敌人
        // Node3D enemy =
        //     (Node3D)enemyPath.GetChildren().Last();
        _enemyTarget = FindBaseTarget();
        if (_enemyTarget != null)
        {
            _turretBase.LookAt(_enemyTarget.GlobalPosition, Vector3.Up, true);
        }
    }

    public void OnTimerTimeout()
    {
        // 没有目标，停止射击
        if (_enemyTarget != null)
        {
            Area3D shot = (Area3D)_projectilePrefab.Instantiate();
            AddChild(shot);
            Projectile projectileCs = shot as Projectile;
            // 该节点的全局位置,让子弹从炮塔出来
            shot.GlobalPosition = _cannon.GlobalPosition;
            // 射击方向，设计方向是大炮的世界坐标的Z轴方向
            // projectileCs.direction = Basis.Z;
            if (projectileCs != null) projectileCs.Direction = _turretBase.GlobalTransform.Basis.Z;
            _animationPlayer.Play("fire");
        }
    }


    // 永远打最前面一个敌人
    public PathFollow3D FindBaseTarget()
    {
        PathFollow3D bestTarget = null;
        float baseProgress = 0.0f;
        foreach (Node enemy in EnemyPath.GetChildren())
        {
            if (enemy is PathFollow3D)
            {
                PathFollow3D enemyPf = enemy as PathFollow3D;
                // 返回2个向量之间的距离
                float distanceTo = GlobalPosition.DistanceTo(enemyPf.GlobalPosition);
                if (enemyPf.Progress > baseProgress && distanceTo <= _turretRange)
                {
                    bestTarget = enemyPf;
                    baseProgress = enemyPf.Progress;
                }
            }
        }

        return bestTarget;
    }
}